package com.gztms.config;

import com.gztms.handler.AccessDeniedHandlerImpl;
import com.gztms.handler.AuthenticationEntryPointImpl;
import com.gztms.handler.UserLoginFailHandler;
import com.gztms.usermgnt.filter.JwtAuthenticationTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author Zoey
 * @date 2023/3/5 16:35
 * @Description
 **/
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
    @Autowired
    private AuthenticationEntryPointImpl authenticationEntryPoint;
    @Autowired
    private AccessDeniedHandlerImpl accessDeniedHandler;
    /** 自定义登录失败处理器*/
    @Autowired
    private UserLoginFailHandler userLoginFailHandler;


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //关闭csrf
                .csrf().disable()
                //不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 对于登录接口 允许匿名访问，即登陆后不能访问。防止登陆后再次登陆
                .antMatchers("/login").anonymous()
                .antMatchers(HttpMethod.GET, // 允许对于网站静态资源的无授权访问
                        "/",
                        "/swagger-ui/",
                        "/swagger-resources/**",
                        "/v2/api-docs/**",
                        "/*.html",
                        "/favicon.ico",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js"
                )
                .permitAll()
                .antMatchers("*/manage/**").hasAnyRole("admin","super_admin")
                .antMatchers("/blog/getHotBlogs").permitAll()
                .antMatchers("/blog/{id}").permitAll()
                .antMatchers("/travel/searchAttrList").permitAll()
                .antMatchers("/travel/findAttrById/{attrId}").permitAll()
                .antMatchers("/blog/getBlogList").permitAll()
                .antMatchers("/user/register").permitAll()
                .antMatchers("/blog/comment/getCommentList").permitAll()
                .antMatchers("/travel/findAllCate").permitAll()
                .antMatchers("/travel/findAllArea").permitAll()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated();

             /*   http.formLogin()
                        .failureHandler(userLoginFailHandler);*/

        //把token校验过滤器添加到过滤器链中
        http.addFilterBefore( jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        // 配置异常处理器
        http.exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint)
                .accessDeniedHandler(accessDeniedHandler);
        // 允许跨域
        http.cors();
    }

    /**
     * 创建PasswordEncoder，并注入容器中
     * @return
     */
    @Bean
    public PasswordEncoder getPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
        web.ignoring().antMatchers("/swagger-ui.html",
                "/v2/api-docs", // swagger api json
                "/swagger-resources/configuration/ui", // 用来获取支持的动作
                "/swagger-resources", // 用来获取api-docs的URI
                "/swagger-resources/configuration/security", // 安全选项
                "/swagger-resources/**",
                "swagger-v2/docs.html",
                "swagger/index.html ",
                "/blog/getHotBlogs"
        );
    }

    public static void main(String[] args) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String s = encoder.encode("123456");
        System.out.println(s);
    }


}
